var express = require('express');
var router = express.Router();
const axios = require('axios');
const chat = require('../config/openAI');
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
  organization: chat.openAI.OrganizationId,
  apiKey: chat.openAI.openAIKey,
});
const openai = new OpenAIApi(configuration);
/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});


router.post('/chat',async function (req,res) {
  let text = req.body.text
  try{
    const response = await openai.createCompletion({
      model: "text-davinci-003",
      prompt: text,
      temperature: 0.9,
      max_tokens: 1000,
    });
    const message = response.data.choices[0].text.trim(); // 提取回复
    res.status(200).json({ message });
  }catch (error) {
    if (error.response) {
      res.status(error.response.status).send(error.response.data);
    } else {
      res.status(500).send(error.message);

    }

  }
})


module.exports = router;
